<template>
  <div class="dataset">

    <!-- 表格工具栏 -->
    <a-row type="flex" justify="space-between">
      <a-col :span="2">
        <a-button type="primary" size="small" style="fontSize: 13px" @click="showNewDatasetModal">
          <template #icon><PlusOutlined /></template>
          <span style="margin-left: 4px">新建数据集</span>
        </a-button>
        <!-- 新建数据集模态框 -->
        <a-modal
          title="新建数据集"
          v-model:visible="newdata_modal.visible"
          :confirm-loading="newdata_modal.confirmLoading"
          @ok="handleNewDatasetOk(newdata_modal.form)"
        >
          <!-- 表单 -->
          <a-form
            :model="newdata_modal.form"
            :rules="newdata_modal.rules"
            :label-col="newdata_modal.labelCol"
            :wrapper-col="newdata_modal.wrapperCol"
          >
            <!-- 数据集名称 -->
            <a-form-item ref="name" label="Dataset" name="name">
              <a-input v-model:value="newdata_modal.form.name" />
            </a-form-item>
            <!-- 数据集备注 -->
            <a-form-item label="Describe" name="desc">
              <a-textarea v-model:value="newdata_modal.form.desc" />
            </a-form-item>
          </a-form>
        </a-modal>
      </a-col>
      <a-col :span="4" :offset="17">
        <a-input-search
          style="height: 24px; width: 180px"
          placeholder="请输入数据集名称搜索"
        >
        </a-input-search>
      </a-col>
      <a-col :span="1">
        <a-button size="small" style="fontSize: 12px" @click="flushDataset">
          <template #icon><ReloadOutlined /></template>
        </a-button>
      </a-col>
    </a-row>

    <!-- 表格部分 -->
    <a-row>
      <a-col :span="24">
        <a-table :columns="columns" :data-source="data" :rowKey="record => record.name"> 

          <!-- 数据集名称插槽，增加 a 标签 -->
          <template #name="{ text }">
            <a>{{ text }}</a>
          </template>
          
          <!-- 操作 action 插槽 -->
          <template #action="{text, record}">
            <a @click="showUpdateModal(record.name)">上传</a>
            <a-modal
              v-model:visible="update_modal.visible"
              title="上传数据"
            >
              <a-upload
                list-type="picture-card"
                v-model:fileList="fileList"
                @change="handleUpdateChange"
                :multiple="true"
                :beforeUpload="beforeUpload"
              >
                <!-- <div v-if="fileList.length < 8"> -->
                <plus-outlined />
                <div class="ant-upload-text">Upload</div>
                <!-- </div> -->
              </a-upload>
              <template #footer>
                <a-button key="back" @click="update_modal.visible = !update_modal.visible">
                  取消
                </a-button>
                <a-button key="submit" type="primary" 
                  :loading="uploading" 
                  :disabled="fileList.length === 0"
                  @click="handleUpload">
                  {{ uploading ? '上传中...' : '上传' }}
                </a-button>
              </template>
            </a-modal>
            <a-divider type="vertical" />
            <!-- <a @click="deleteDataset(record.name)">删除</a> -->
            <a @click="deleteConform(record.name)">删除</a>

          </template>
        </a-table>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import axios from "axios"
import { PlusOutlined, ReloadOutlined, ExclamationCircleOutlined, InboxOutlined } from '@ant-design/icons-vue'
import { createVNode } from 'vue';
import { Modal } from 'ant-design-vue';
import { message } from 'ant-design-vue';
import qs from 'qs';

const columns = [
  {
    title: '数据集名称', 
    dataIndex: 'name', 
    key: 'name',
    slots: { customRender: 'name' }
  },
  {
    title: '数据量',
    dataIndex: 'data_row', 
    key: 'data_row',
  },
  {
    title: '描述',
    dataIndex: 'desc',
    key: 'desc',
  }, 
  {
    title: '创建时间',
    dataIndex: 'create_time', 
    key: 'create_time',
    width: 200
  },
  {
    title: '更新时间',
    dataIndex: 'update_time', 
    key: 'update_time',
    width: 200
  },
  {
    title: '操作',
    dataIndex: 'action',  
    key: 'action',
    slots: { customRender: 'action' },
  },
]

const data = [
  // {
  //   name: 'coco',
  //   data_row: 11,
  //   desc: 'coco测试数据集', 
  //   create_time: '2020年11月11日15:11:05',
  //   update_time: '2020年11月11日15:45:56'
  // },
]

export default {
  components: {
    PlusOutlined, ReloadOutlined, InboxOutlined, ExclamationCircleOutlined
  },
  data() {
    return {
      // '新建数据集'模态框
      newdata_modal: {
        visible: false, 
        confirmLoading: false,  
        form: {
          name: '',  // 数据集名称
          desc: '',  // 数据集备注
        },
        labelCol: { span: 6 },
        wrapperCol: { span: 15 },
        rules: {
          name: [
              { required: true, 
                message: 'Please enter your dataset name. ', 
                trigger: 'blur' 
              },
          ],
        },
      
      },

      // 数据展示
      columns, data,
      
      // 上传图片模态框
      update_modal: {
        visible: false,
        name: '',
      },

      // 上传文件列表
      fileList: [],
      uploading: false,
    }
  }, 
  methods: {
    // ‘新建数据集’模态框显示
    showNewDatasetModal() {
      this.newdata_modal.visible = true;
    },
    // 新建数据集模态框确定
    handleNewDatasetOk(form) {
      this.newdata_modal.confirmLoading = true;
      // 取得表单数据，与后端进行交互
      this.$axios.post(
        '/dataset/create',
        {
          name: form.name,
          desc: form.desc,
        }
      ).then(response => {
        // console.log(response.data);
        this.newdata_modal.visible = false;
        this.newdata_modal.confirmLoading = false;
        this.flushDataset();
      }).catch(error => {
        console.log(error);
      });
    },
    // 处理数据刷新
    flushDataset() {
      this.$axios.get('/dataset/rechieve')
      .then(response =>{
        // console.log(response.data);
        this.data = response.data;
      }).catch(error => {
        console.log(error)
      })
    },
    // 删除数据集
    deleteDataset(name) {
      this.$axios({url: '/dataset/delete', params: {name: name}})
      .then(response =>{
        // console.log(response.data);
        this.flushDataset();
      }).catch(error => {
        console.log(error)
      })
    },
    // 删除警示
    deleteConform(name) {
      let that = this
      Modal.confirm({
        title: '确定删除提示',
        icon: createVNode(ExclamationCircleOutlined),
        content: '确定删除数据集"' + name + '"吗？删除后将不可恢复！',
        onOk() {
          that.deleteDataset(name)
        },
        onCancel() {},
      });
    },
    // 上传模态框
    showUpdateModal(name) {
      this.update_modal.visible = true;
      this.update_modal.name = name;
    },
    // 上传数据
    updateDataset(name) {
      this.$axios({url: '/dataset/update', params: {name: name}})
      .then(response =>{
        // console.log(response.data);
        this.flushDataset();
      }).catch(error => {
        console.log(error)
      })
    },
    handleUpdateChange(info) {
      const status = info.file.status;
      if (status !== 'uploading') {
        // console.log(info.file);
        // console.log(info.fileList);
      }
      if (status === 'done') {
        message.success(`${info.file.name} file uploaded successfully.`);
      } else if (status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
      }
    },
    beforeUpload(file){
      this.fileList = [...this.fileList, file];
      return false;
    },
    handleUpload(){
      const { fileList } = this;
      const formData = new FormData();
      formData.append('name', this.update_modal.name);
      fileList.forEach(file => {
        formData.append('file', file.originFileObj);
        // console.log(file.originFileObj);
      });
      // console.log(formData.get('name'));
      this.uploading = true;
      
      this.$axios({
        url: '/dataset/update',
        // processData: false,
        data: formData, 
        method: 'post',
        // headers: {'Content-Type':'multipart/form-data'}
      })
      .then(response =>{
        this.fileList = [];
        // console.log(response.data);
        if(response.data.status === 'success')
          message.success('upload successfully.');
        else
          message.error(response.data.error)
      }).catch(error => {
        console.log(error);
        message.success('upload failed.');
      });
      this.uploading = false;
      this.update_modal.visible = false;
      this.flushDataset();
    }
  },
  mounted() {
    this.flushDataset()
  }, 
}
</script>

<style scoped>

  .dataset {
    padding: 16px;
  }

  /deep/ .ant-row {
    padding-bottom: 10px;
  }

  /deep/ .ant-input {
    font-size: 12px;
  }

  /deep/ .ant-table {
    font-size: 14px;
  }

  /deep/ .ant-table-thead > tr > th, /deep/ .ant-table-tbody > tr > td {
    padding: 10px;
    height: 40px;
  }

  /deep/ .ant-table-thead > tr > th {
    border-right: 1px solid #fff;
  }

</style>